var data1 = []
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate,invoiceNumber = getQueryVariable("invoiceNumber"), cuName = getQueryVariable("customerName");
var isMsn="否";
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});
let getSTreeElem;//业务员下拉框对象
let getOTreeElem;//操作员下拉框对象

let deptOperationList;
let deptSalesmanList;
function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if (cuName!=null && cuName!=''){
            tmparr.selected=true;
        }
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}

function getTreeList(el,name, data) {
    for (let i in data) {
        data[i].selected=true;
    }
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
             return this
        }
    })
}

//select over
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();
    if (cuName!=null && cuName!=''){
        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            getOTreeElem = getxmselect("#operationCode", "operationCode", userTree);
            getSTreeElem = getTreeList("#salesmanCode", "salesmanCode", userTree);
        } else {
            getOTreeElem = getxmselect("#operationCode", "operationCode", [{name: user.name, value: user.code}]);
            getSTreeElem = getTreeList("#salesmanCode", "salesmanCode", [{name: user.name, value: user.code}]);
        }
    }else {
        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            getOTreeElem = getxmselect("#operationCode", "operationCode", userTree);
            getSTreeElem = getxmselect("#salesmanCode", "salesmanCode", userTree);
        } else {
            getOTreeElem = getxmselect("#operationCode", "operationCode", [{name: user.name, value: user.code}]);
            getSTreeElem = getxmselect("#salesmanCode", "salesmanCode", [{name: user.name, value: user.code}]);
        }
    }

    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }


})()

form.render();//表单刷新

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}
//判断当前登录用户是否为 营销部门的总监 角色 true:是 false 否
let isMarketingDirector = false;

//判断当前登录用户是否为 营销部门的总监 角色
function is_marketing_director() {
    $.ajax({
        url: 'customer/isMarketingDirector',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                isMarketingDirector = da.data;
            }
        }
    });
}

//判断当前登录用户是否为 财务
let isFinance = false;

//判断当前登录用户是否为 财务
function checkIsFinance(){
    $.ajax({
        url: 'cost/isFinance',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            if("是" === date.data){
                isFinance = true;
            }
        }
    })
}

//判断该用户是否含有总监，财务，管理员角色 true:是 false 否
let isUerRoles = false;
//判断该用户是否含有总监，财务，管理员角色 true:是 false 否
function is_user_roles() {
    $.ajax({
        url: 'billChange/isUerRoles',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                isUerRoles = da.data;
            }
        }
    });
}

var data2=[];

function initTable(obj){
    table.render({
        elem: '#foreignexchangesettlementselect'
        ,where:obj
        ,url:'billChange/selectAllchangeByPage'
        ,toolbar: '#foreignexchangesettlementtoolbar'
        ,totalRow: true
        ,cols: [[
            {checkbox: true, fixed: true, totalRowText: '合计'}
            ,{field:'billType', title:'单据类型',sort:true,width: 120,templet: function(d){
                    var re=""
                    if(d.status==1){
                        re="草稿箱"
                    }else if(d.status==2){
                        re="待批箱"
                    }else if(d.status==3){
                        re="已批箱"
                    }else if(d.status==4){
                        re="完成箱"
                    }else if(d.status==5){
                        re="垃圾箱"
                    }
                    return re;
                }}
            ,{field:'companyName', title:'签约公司 ',sort:true,width: 120}
            ,{field:'invoiceNo', title:'发票编号',sort:true,width: 120,event: "invoicenumber"}
            ,{field:'customerName', title:'客户名称',sort:true,width: 120}
            ,{field:'customerLevelName', title:'客户级别',sort:true,width: 120}
            ,{field:'invoiceDate', title:'发票日期',sort:true,width: 120}
            ,{field:'shippingDate', title:'出运日期',sort:true,width: 120}
            ,{field:'settleDate', title:'预计收汇日期',sort:true,width: 120}
            ,{field:'moneyKind', title:'币种',sort:true,width: 120}
            ,{field:'invoiceMoney', title:'发票总额',sort:true,width: 120, totalRow: true}
            ,{field:'actualAtd', title:'实际开船日期ATD ',sort:true,width: 200}
            ,{field:'instockDate', title:'进仓装柜日期 ',sort:true,width: 180}
            ,{field:'settleMode', title:'收款(结汇)方式',sort:true,width: 120}
            ,{field:'priceTerm', title:'价格术语',sort:true,width: 120}
            ,{field:'createTime', title:'制单日期',sort:true,width: 120}
            ,{field:'contractNo', title:'销售合同号',sort:true,width: 120}
            ,{field:'custContractNo', title:'客户合同号',sort:true,width: 120}
            ,{field:'salesman', title:'业务员',sort:true,width: 120}
            ,{field:'businessMode', title:'业务模式',sort:true,width: 120}
            ,{field:'asPerInNo', title:'备注',sort:true,width: 140}
            ,{field:'stock', title:'仓库',sort:true,width: 120}
            ,{field:'overdue', title:'逾期',sort:true,width: 120}
            ,{field:'payday', title:'账期',sort:true,width: 120}
            ,{field:'bankName', title:'银行 ',sort:true,width: 120}
            ,{field:'opname', title:'操作员',sort:true,width: 120}
            ,{field:'totalTariffAmount', title:'关税总金额',sort:true,width: 120}
            ,{field:'usdRate', title:'美元汇率',sort:true,width: 120}
            ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120}
            ,{field:'startPlace', title:'起运地',sort:true,width: 120}
            ,{field:'endPlace', title:'目的地',sort:true,width: 120}
            // ,{fixed: 'right', width:240, toolbar: '#foreignexchangesettlementeditor', title:'操作'}
            ,{field:'whetherCreditGuarantee', title:'走信保订单', templet: function(d){
                    if(d.whetherCreditGuarantee==0){
                        return "否"
                    }else if(d.whetherCreditGuarantee==1){
                        return "是(采购抬头：上海沣奇)"
                    }else if(d.whetherCreditGuarantee==2){
                        return "是(采购抬头：上海源铢)"
                    }else{
                        return ""
                    }

                }}
            ,{field:'creditGuaranteeAmount', title:'信保订单金额USD',sort:true,width: 120}
            ,{fixed: 'right', width:240, title:'操作', templet: function(d){
                    if(isMsn=="是"){
                        var html="<div>"
                        //是否为总监或财务
                        let flag = isMarketingDirector || isFinance
                        if ((d.status == 1 || d.status == 2 || d.status == 3) && flag) {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                        }
                        if(d.status==1){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>"
                        }

                        if ((d.status == 2 || d.status == 3) && flag) {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                        }

                        if(d.status==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                        }
                        if(d.status==1){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delete\">删除</a>"
                        }
                        if(d.status==5){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delectYes\">彻底删除</a><a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"reduction\">还原</a>"
                        }
                        return html+"</div>";
                    }else {
                        var html = "<div>"
                        if (d.status == 1 || d.status == 2) {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                        }
                        if (d.status == 1) {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>"
                        }
                        return html + "</div>";
                    }
                }
            }
        ]]
        ,id: 'foreignexchangesettlementtableid'
        ,height: $(document).height() - $('#foreignexchangesettlementselect').offset().top - 50
        ,page: true
        ,limit: 50
        ,limits:[50, 100, 200, 300, 500, 1000]
    });
    if(controlShow==0){
        $("#allOpen").hide()
        $("#allClost").hide()
    }
}





table.on('tool(foreignexchangesettlementtable)', function(obj){
    var data = obj.data;
    var id=obj.data.billId;
    if(obj.event === 'update') {
                parent.intab("views/jsp/ExportBusiness/tpl/newupforeignexchangeset.jsp?id="+id,"修改结汇")
    }else if(obj.event === 'delectYes'){
        layer.confirm('真的删除行么', function (index) {
            $.ajax({
                url: 'billChange/deleteBillById?billId='+id,
                type: 'GET',
                success: function (date) {
                    layer.msg('删除成功');
                }
            });
            obj.del();
            layer.close(index);
        });
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', function (index) {
            changeStatues(id,3)
            layer.msg('提交审批');
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', function (index) {
            changeStatues(id,3)
            layer.msg('审批通过');
        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定审批退回吗', function (index) {
            $.ajax({
                url: 'billChange/findReceive?invoiceNumber='+data.invoiceNo,
                type: 'GET',
                success: function (date) {
                    if(date.data==""){
                        changeStatues(id,1)
                        layer.msg('审批退回');
                    }else{
                        layer.msg(date.data)
                    }
                }
            });
        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', function (index) {
            changeStatues(id,4)
            layer.msg('完成');
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', function (index) {
            changeStatues(id,1)
            layer.msg('还原');
        });
    }else if(obj.event === 'delete'){
        layer.confirm('确定删除吗', function (index) {
            changeStatues(id,5)
            layer.msg('删除');
        });
    }else if (obj.event === "invoicenumber"){
        parent.intab("views/jsp/ExportBusiness/tpl/viewforeignexchangesettlement.jsp?id="+id,"结汇明细")
    }
    form.render()
});

function changeStatues(id,statues){
    $.ajax({
        url: 'billChange/changeBillById?billId='+id+"&statues="+statues,
        type: 'GET',
        success: function (date) {
            table.reload("foreignexchangesettlementtableid",{
                url: 'billChange/selectAllchangeByPage'
            })
        }
    });
}

layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("costStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/ExportBusiness/foreignexchangesettlement1.jsp","结汇发票费用统计")
                break
            case "s2":
                parent.intab("views/jsp/ExportBusiness/foreignexchangesettlement2.jsp","结汇单据产品统计")
                break
            case "shipmentIsBillExchangeStatistics":
                parent.intab("views/jsp/ExportBusiness/tpl/shipmentIsBillExchangeStatistics.jsp","出运是否结汇统计")
                break
        }
    });
})

form.on('submit(submitform)', function(data){
    let operationCode = data.field.operationCode;
    let salesmanCode = data.field.salesmanCode;
    if(salesmanCode==""&&operationCode==""){
        var sm = getManageRule("BillExchangeSm")//业务员
        var codeList =""
        for(let i in sm){
            if(codeList==""){
                codeList = sm[i].code;
            }else{
                codeList = codeList + "," + sm[i].code;
            }
        }
        data.field.salesmanCode = codeList;
        var op = getManageRule("BillExchangeOp");//操作员
        var codeList =new Array();
        for(let i in op){
            if(codeList==""){
                codeList = op[i].code;
            }else{
                codeList = codeList + "," + op[i].code;
            }
        }
        data.field.operationCode = codeList;
    }

    // table.reload('foreignexchangesettlementtableid', {
    //     data:data1 ,
    //     page: {
    //         curr: 1 //重新从第 1 页开始
    //     }
    //     ,where: data.field
    // }, 'data');
    initTable(data.field);

    return false;
});

layui.use(['dropdown'], function () {
    var dropdown = layui.dropdown;
    dropdown.onFilter("printfn", function (event) {
        var checkStatus = table.checkStatus("foreignexchangesettlementtableid");
        $.ajax({
            url: 'billChange/selectLogo?declare_id='+checkStatus.data[0].billId,
            type: 'GET',
            async: false, // 同步
            success: function (date) {
            },
        });
        switch (event) {
            case "printfn1":
                console.log(checkStatus.data.length)
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个结汇单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的结汇单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=billExchange1&code=code:"+checkStatus.data[0].billId)
                break;
            case "printfn2":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个结汇单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的结汇单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=billExchange2&code=code:"+checkStatus.data[0].billId)
                break;
        }
    });
})
function downLogo(url){
    $.ajax({
        url: 'ftp/onLine2?pathString='+url,
        type: 'GET',
        async: false, // 同步
        success: function (date) {
        },
    });
}


table.on('toolbar(foreignexchangesettlementtable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/ExportBusiness/tpl/newupforeignexchangesettlement.jsp","新增结汇")
            break;
        case 'allOpen':
            var checkStatus = table.checkStatus("foreignexchangesettlementtableid");
            var allID="";
            for(let i in checkStatus.data){
                allID+=checkStatus.data[i].billId+","
            }
            $.ajax({
                url: 'billChange/checkAllStatus?id='+allID+"&type=完成",
                type: 'GET',
                async: false, // 同步
                success: function (date) {
                    if(date.data=="success"){
                        layer.msg("操作成功")
                        table.reload("foreignexchangesettlementtableid",{
                            url: 'billChange/selectAllchangeByPage'
                        })
                    }else{
                        layer.msg("操作失败")
                    }
                }
            })
            break;
        case 'allClost':
            var checkStatus = table.checkStatus("foreignexchangesettlementtableid");
            var allID="";
            for(let i in checkStatus.data){
                allID+=checkStatus.data[i].billId+","
            }
            $.ajax({
                url: 'billChange/checkAllStatus?id='+allID+"&type=已批",
                type: 'GET',
                async: false, // 同步
                success: function (date) {
                    if(date.data=="success"){
                        layer.msg("操作成功")
                        table.reload("foreignexchangesettlementtableid",{
                            url: 'billChange/selectAllchangeByPage'
                        })
                    }else{
                        layer.msg("操作失败")
                    }
                }
            })
            break;
    };
});

$("#statistical").on("click",function () {
    parent.intab("views/jsp/ExportBusiness/tpl/statistics.jsp","结汇统计")
});
$("#settlementexchangetargets").on("click",function () {
    parent.intab("views/jsp/ExportBusiness/tpl/settlementexchangetargets.jsp","结汇目标")
});
$("#clear").on("click",function () {
    getOTreeElem.setValue([ ]);
    getSTreeElem.setValue([ ]);
    deptOperationList.setValue([ ]);
    deptSalesmanList.setValue([ ]);
});
var controlShow=0;
$(document).ready(function () {
    //判断是否显示一键功能
   var roles=user.roles
   var ss= roles.split(",")

   for(let i in ss){
      if(ss[i]=="admin"||ss[i]=="CW01"){
          controlShow=1
      }
   }
   if(controlShow==0){
       $("#allOpen").hide()
       $("#allClost").hide()
   }
    $.ajax({
        url: 'billChange/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn=date.data
        }
    })
    $.ajax({
        url: 'billChange/selectAllcompanyAndpeople',
        type: 'GET',
        success: function (date) {
            var map=date.data
            var company=[]
            $.each(map, function (key, value) {
                if(key=="companyName"){
                    company=value
                }
            });
            for(let i in company){
                $("#company_code").append("<option value='"+company[i].code+"'>"+company[i].name+"</option>")
            }

            form.render();
        }
    });

    //判断当前登录用户是否为 营销部门的总监 角色
    is_marketing_director();

    //判断当前登录用户是否为 财务
    checkIsFinance();

    //判断该用户是否含有营销总监，财务，管理员角色 true:是 false 否
    is_user_roles();

    if (isUerRoles){
        document.getElementById("show1").style.display="block"
    }else {
        document.getElementById("show2").style.display="block"
    }

    let whereData={};
    if (cuName!=null && cuName!=''){
        let cName = decodeURI(cuName);
        $("#bill").val(cName);

        let salesmanCode = getSTreeElem.getValue('value').join();
        let operationCode = getOTreeElem.getValue('value').join();
        whereData.salesmanCode= salesmanCode
        whereData.operationCode= operationCode

        whereData.bill= cName
    }else {
        $("#bill").val(invoiceNumber);

        whereData.bill=invoiceNumber;
    }

    initTable(whereData);
});
